package org.karn.example.content_provider;

import android.content.Context;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.provider.Browser;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.TextView;


public class MyCursorAdapter extends BaseAdapter {

    Context mContext;
    LayoutInflater inflater;
    Cursor mCursor;
    
    public MyCursorAdapter (Context context, Cursor c)
    {
        mContext = context;
        mCursor  = c;
        inflater = LayoutInflater.from(mContext);
    }

    @Override
    public int getCount ( )
    {
        return mCursor.getCount();
    }

    @Override
    public Object getItem (int arg0)
    {
        return null;
    }

    @Override
    public long getItemId (int arg0)
    {
        return 0;
    }
    
    @Override
    public View getView (int position, View convertView, ViewGroup parent)
    {
        ViewHolder holder;
        if(convertView == null)
        {
            holder       = new ViewHolder();
            convertView  = inflater.inflate(R.layout.list_item, null);
            holder.title = (TextView) convertView.findViewById(R.id.titleTxt);
            holder.url   = (TextView) convertView.findViewById(R.id.urlTxt);
            holder.image = (ImageView) convertView.findViewById(R.id.image);
            
            convertView.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }
        
        mCursor.moveToPosition(position);
        holder.title.setText(mCursor.getString(mCursor.getColumnIndex(
                Browser.BookmarkColumns.TITLE)));
        holder.url.setText(mCursor.getString(mCursor.getColumnIndex(
                Browser.BookmarkColumns.URL)));
        
        byte[] favIconBuffer = mCursor.getBlob(mCursor.getColumnIndex(
                Browser.BookmarkColumns.FAVICON));
        
        if(favIconBuffer != null)
        {
            holder.image.setImageBitmap(BitmapFactory.decodeByteArray(
                    favIconBuffer,0, favIconBuffer.length));
        }
        else
        {
            holder.image.setImageResource(R.drawable.ic_launcher);
        }
        
        return convertView;
        
    }
    
    class ViewHolder {
        TextView title, url;
        ImageView image;
    }

}
